﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using WmsApp.Exceptions;
using WmsApp.Export;
using WmsApp.Factory;
using WmsApp.Lookup;
using WmsApp.Report;
using WmsApp.Service;
using WmsApp.UI;
using WmsApp.Window;
using WmsApp.Window.Editor;
using WmsApp.WindowControl.PriceAndAmount;
using WmsApp.WmsService;
using WmsApp.StaticData;

namespace WmsApp.WindowControl
{
    public class OutStoreBillController
    {
        //private LookUpEdit providerLookUpEdit = null;
        //private TextEdit providerNameTextEdit = null;
        //出库单日期
        private readonly DateEdit billDateDateEdit;
        private readonly ComboBoxEdit comboBoxEditDepartment3;
        private readonly ComboBoxEdit comboBoxEditGetID3;
        //出库日期
        private readonly DateEdit outBillDateDateEdit;
        private readonly GridControl outBillDtlGridControl;
        private readonly TextEdit outBillIdTextEdit;
        private readonly TextEdit outBillStateDescTextEdit;
        private readonly LookUpEdit outStoreTypeLookUpEdit;
        private readonly TextEdit textEditProjectNo3;
        private readonly TextEdit textEditPurpose3;
        private readonly TextEdit textEditRequisitionNo3;
        private ControlType _controlType = ControlType.None;
        private OutStoreBillWrap _wrap;
        private LookUpEdit lookUpEditGetID3;
        private TextEdit textEditGetName3;

        /// <summary>
        ///   最后归还日期和故障原因的复合控件
        /// </summary>
        public BorrowRepairEditor FBorrowRepairEditor { get; set; }

        /// <summary>
        ///   标签，项目管理号或者是维修商。
        /// </summary>
        public LabelControl FProjectNoOrRepairTrade { get; set; }

        /// <summary>
        ///   return the RepositoryItemGridLookUpEdit
        /// </summary>
        public RepositoryItemGridLookUpEdit FRepositoryItemGridLookUpEdit { get; private set; }

        public string CurrentBillID
        {
            get { return _wrap.POutStoreBill.BillID; }
        }

        public string BillState
        {
            get { return _wrap.POutStoreBill.BillState; }
        }

        #region Tax

        public void InStoreBillController_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            #region Deleted

            ////31TaxRate32PriceTax33PriceNotTax34AmountTax35AmountNotTax36Quantity
            //if (e.Column.FieldName == "TaxRate")
            //{
            //    decimal value = (decimal)e.Value;
            //    if (GetValue(e.RowHandle, "PriceTax") > 0 && GetValue(e.RowHandle, "Quantity") > 0)
            //    {
            //        PriceAndAmountArithBase arith = new Tax(value, GetValue(e.RowHandle, "PriceTax"),
            //                                                GetValue(e.RowHandle, "Quantity"));
            //        SetValue(e.RowHandle, "AmountTax", arith.AmountTax);
            //    }
            //    if (GetValue(e.RowHandle, "PriceNotTax") > 0 && GetValue(e.RowHandle, "Quantity") > 0)
            //    {
            //        PriceAndAmountArithBase arith = new NotTax(value, GetValue(e.RowHandle, "PriceNotTax"),
            //                                             GetValue(e.RowHandle, "Quantity"));
            //        SetValue(e.RowHandle, "AmountNotTax", arith.AmountNotTax);
            //    }
            //}
            //else if (e.Column.FieldName == "PriceTax")
            //{
            //    decimal value = (decimal)e.Value;
            //    PriceAndAmountArithBase arith = new Tax(GetValue(e.RowHandle, "TaxRate"), value,
            //                                            GetValue(e.RowHandle, "Quantity"));
            //    SetValue(e.RowHandle, "PriceNotTax", arith.PriceNotTax);
            //    SetValue(e.RowHandle, "AmountTax", arith.AmountTax);
            //    SetValue(e.RowHandle, "AmountNotTax", arith.AmountNotTax);
            //}
            //else if (e.Column.FieldName == "PriceNotTax")
            //{
            //    decimal value = (decimal)e.Value;
            //    PriceAndAmountArithBase arith = new NotTax(GetValue(e.RowHandle, "TaxRate"), value,
            //                                            GetValue(e.RowHandle, "Quantity"));
            //    SetValue(e.RowHandle, "PriceTax", arith.PriceTax);
            //    SetValue(e.RowHandle, "AmountTax", arith.AmountTax);
            //    SetValue(e.RowHandle, "AmountNotTax", arith.AmountNotTax);
            //}
            //else if (e.Column.FieldName == "Quantity")
            //{
            //    decimal value = (decimal)e.Value;
            //    if (GetValue(e.RowHandle, "PriceTax") > 0 && GetValue(e.RowHandle, "Quantity") > 0)
            //    {
            //        PriceAndAmountArithBase arith = new Tax(GetValue(e.RowHandle, "TaxRate"), GetValue(e.RowHandle, "PriceTax"),
            //                                               value);
            //        SetValue(e.RowHandle, "AmountTax", arith.AmountTax);
            //    }
            //    if (GetValue(e.RowHandle, "PriceNotTax") > 0 && GetValue(e.RowHandle, "Quantity") > 0)
            //    {
            //        PriceAndAmountArithBase arith = new NotTax(GetValue(e.RowHandle, "TaxRate"), GetValue(e.RowHandle, "PriceNotTax"),
            //                                             value);
            //        SetValue(e.RowHandle, "AmountNotTax", arith.AmountNotTax);
            //    }
            //}

            #endregion

            if (e.Column.FieldName == "Quantity")
            {
                var value = (decimal) e.Value;
                if (GetValue(e.RowHandle, "PriceTax") > 0 && GetValue(e.RowHandle, "Quantity") > 0)
                {
                    //PriceAndAmountArithBase arith = new PriceAndAmountArithTax(GetValue(e.RowHandle, "TaxRate"), GetValue(e.RowHandle, "PriceTax"),
                    //                                       value);

                    var arith = ArithFactory.CreatePriceAndAmountArith(true, GetValue(e.RowHandle, "TaxRate"),
                                                                       GetValue(e.RowHandle, "PriceTax"),
                                                                       value);

                    SetValue(e.RowHandle, "AmountTax", arith.AmountTax);
                }
                if (GetValue(e.RowHandle, "PriceNotTax") > 0 && GetValue(e.RowHandle, "Quantity") > 0)
                {
                    //PriceAndAmountArithBase arith = new PriceAndAmountArithNotTax(GetValue(e.RowHandle, "TaxRate"), GetValue(e.RowHandle, "PriceNotTax"),
                    //                                     value);

                    var arith = ArithFactory.CreatePriceAndAmountArith(false, GetValue(e.RowHandle, "TaxRate"),
                                                                       GetValue(e.RowHandle, "PriceNotTax"),
                                                                       value);

                    SetValue(e.RowHandle, "AmountNotTax", arith.AmountNotTax);
                }
            }
        }

        private decimal GetValue(int row, string fieldName)
        {
            var gv = (GridView) outBillDtlGridControl.MainView;
            var entity = gv.GetRow(row);
            var obj = entity.GetType().GetProperty(fieldName).GetValue(entity, null);
            return (decimal) obj;
        }

        private void SetValue(int row, string fieldName, decimal value)
        {
            var gv = (GridView) outBillDtlGridControl.MainView;
            var entity = gv.GetRow(row);
            entity.GetType().GetProperty(fieldName).SetValue(entity, value, null);
        }

        #endregion

        #region 构造函数

        public OutStoreBillController(TextEdit outBillIDTextEdit,
                                      /*LookUpEdit providerLookUpEdit, TextEdit providerNameTextEdit, */
                                      DateEdit billDateDateEdit,
                                      TextEdit outBillStateDescTextEdit, GridControl outBillDtlGridControl,
                                      LookUpEdit outStoreTypeLookUpEdit,
                                      TextEdit textEditGetName3, TextEdit textEditProjectNo3, TextEdit textEditPurpose3,
                                      TextEdit textEditRequisitionNo3,
                                      ComboBoxEdit comboBoxEditDepartment3, LookUpEdit lookUpEditGetID3,
                                      DateEdit outBillDateDateEdit, ComboBoxEdit comboBoxEditGetID3)
        {
            this.textEditGetName3 = textEditGetName3;
            this.textEditProjectNo3 = textEditProjectNo3;
            this.textEditPurpose3 = textEditPurpose3;
            this.textEditRequisitionNo3 = textEditRequisitionNo3;
            this.comboBoxEditDepartment3 = comboBoxEditDepartment3;
            this.lookUpEditGetID3 = lookUpEditGetID3;

            this.outBillDtlGridControl = outBillDtlGridControl;
            this.billDateDateEdit = billDateDateEdit;
            this.outBillDateDateEdit = outBillDateDateEdit;
            outBillIdTextEdit = outBillIDTextEdit;
            this.outBillStateDescTextEdit = outBillStateDescTextEdit;
            //this.providerLookUpEdit = providerLookUpEdit;
            //this.providerNameTextEdit = providerNameTextEdit;
            this.outStoreTypeLookUpEdit = outStoreTypeLookUpEdit;

            this.comboBoxEditGetID3 = comboBoxEditGetID3;

            //LookupBind.BindingLookUpEditSystemUser(this.lookUpEditGetID3, this.textEditGetName3, "GetName");

            //LookupBind.BindingLookUpEditProvider(this.providerLookUpEdit, providerNameTextEdit);
            LookupBind.BindingLookUpEditOutStoreType(this.outStoreTypeLookUpEdit);
            //FRepositoryItemGridLookUpEdit =
            //    LookupBind.BindingLookUpEditGoodsCodeType((GridView) outBillDtlGridControl.MainView,
            //                                              ((GridView) outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn24"),
            //                                              //((GridView) outBillDtlGridControl.MainView).Columns.
            //                                              //    ColumnByName("gridColumn25"),
            //                                              //((GridView) outBillDtlGridControl.MainView).Columns.
            //                                              //    ColumnByName("gridColumn26"),
            //                                                   ((GridView)outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn26"),
            //                                              ((GridView)outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn25"),
            //                                              ((GridView) outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn29"),
            //                                              ((GridView) outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn30"),
            //                                              ((GridView) outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn27"),
            //                                              ((GridView) outBillDtlGridControl.MainView).Columns.
            //                                                  ColumnByName("gridColumn28")
            //        );
            LookupBind.BindingLookUpEditStoreType(
                (GridView) outBillDtlGridControl.MainView,
                ((GridView) outBillDtlGridControl.MainView).Columns.ColumnByName("gridColumn27"),
                ((GridView) outBillDtlGridControl.MainView).Columns.ColumnByName("gridColumn28")
                );
            ((GridView) outBillDtlGridControl.MainView).CellValueChanged += InStoreBillController_CellValueChanged;
        }

        #endregion

        /// <summary>
        ///   编辑一个出库单
        /// </summary>
        /// <param name = "outStoreBillID"></param>
        public void LoadOutStoreBill(string outStoreBillID)
        {
            var service = EntityServiceFactory.GetWrapService<OutStoreBillWrap, OutStoreBillWrapService>();
            _wrap = service.GetWrap(outStoreBillID);
            _controlType = ControlType.Editing;
            DataBinding();
        }

        private void DataBindingDepatment()
        {
            DistinctEntityBinder.BindingComboBoxEdit(comboBoxEditDepartment3, "OutStoreBill", "Department");
            //var list = Factory.WmsServiceFactory.GetServiceClient().GetOutStoreBillDepts();
            //comboBoxEditDepartment3.Properties.Items.Clear();
            //foreach (var dept in list)
            //{
            //    comboBoxEditDepartment3.Properties.Items.Add(dept);
            //}
        }

        private void DataBinding()
        {
            //绑定部门
            DataBindingDepatment();
            //绑定领用人
            DistinctEntityBinder.BindingComboBoxEdit(comboBoxEditGetID3, "OutStoreBill", "GetName");
            //this.providerLookUpEdit.DataBindings.Clear();
            //this.providerLookUpEdit.DataBindings.Add("EditValue", wrap.POutStoreBill, "ProviderCode");
            //this.providerNameTextEdit.DataBindings.Clear();
            //this.providerNameTextEdit.DataBindings.Add("EditValue", wrap.POutStoreBill, "ProviderName");
            billDateDateEdit.DataBindings.Clear();
            billDateDateEdit.DataBindings.Add("EditValue", _wrap.POutStoreBill, "BillDate");

            outBillDateDateEdit.DataBindings.Clear();
            outBillDateDateEdit.DataBindings.Add("EditValue", _wrap.POutStoreBill, "OutBillDate", true, DataSourceUpdateMode.OnValidation);

            comboBoxEditGetID3.DataBindings.Clear();
            comboBoxEditGetID3.DataBindings.Add("EditValue", _wrap.POutStoreBill, "GetName");

            ////由于OutBillDate是nullable类型的，所以在绑定的时候，出现问题，现在改造如下：
            //this.outBillDateDateEdit.EditValue = wrap.POutStoreBill.OutBillDate;
            //this.outBillDateDateEdit.EditValueChanged += (o, e) =>
            //{
            //    wrap.POutStoreBill.OutBillDate = (DateTime?)this.outBillDateDateEdit.EditValue;
            //};

            outBillIdTextEdit.DataBindings.Clear();
            outBillIdTextEdit.DataBindings.Add("EditValue", _wrap.POutStoreBill, "BillID");
            outBillStateDescTextEdit.DataBindings.Clear();
            outBillStateDescTextEdit.DataBindings.Add("EditValue", _wrap.POutStoreBill, "BillStateDesc");

            //this.textEditGetName3.DataBindings.Clear();
            //this.textEditGetName3.DataBindings.Add("EditValue", wrap.POutStoreBill, "GetName");
            textEditProjectNo3.DataBindings.Clear();
            textEditProjectNo3.DataBindings.Add("EditValue", _wrap.POutStoreBill, "ProjectNo");
            textEditPurpose3.DataBindings.Clear();
            textEditPurpose3.DataBindings.Add("EditValue", _wrap.POutStoreBill, "Purpose");
            textEditRequisitionNo3.DataBindings.Clear();
            textEditRequisitionNo3.DataBindings.Add("EditValue", _wrap.POutStoreBill, "RequisitionNo");
            comboBoxEditDepartment3.DataBindings.Clear();
            comboBoxEditDepartment3.DataBindings.Add("EditValue", _wrap.POutStoreBill, "Department");
            //this.lookUpEditGetID3.DataBindings.Clear();
            //this.lookUpEditGetID3.DataBindings.Add("EditValue", wrap.POutStoreBill, "GetName");

            if (_wrap.POutStoreBill.BillState == Constant.BillStateDraft)
            {
                var gv = ((GridView) outBillDtlGridControl.MainView);
                gv.Columns.ColumnByFieldName("TaxRate").OptionsColumn.AllowEdit = true;
                gv.Columns.ColumnByFieldName("PriceTax").OptionsColumn.AllowEdit = true;
                gv.Columns.ColumnByFieldName("PriceNotTax").OptionsColumn.AllowEdit = true;
                gv.Columns.ColumnByFieldName("Quantity").OptionsColumn.AllowEdit = true;
                gv.Columns.ColumnByFieldName("NewGoodsCode").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("StoreTypeCode").OptionsColumn.AllowEdit = true;
                gv.Columns.ColumnByFieldName("SpecificationType").OptionsColumn.AllowEdit = true;
            }
            else
            {
                var gv = ((GridView) outBillDtlGridControl.MainView);
                gv.Columns.ColumnByFieldName("TaxRate").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("PriceTax").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("PriceNotTax").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("Quantity").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("NewGoodsCode").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("StoreTypeCode").OptionsColumn.AllowEdit = false;
                gv.Columns.ColumnByFieldName("SpecificationType").OptionsColumn.AllowEdit = false;
            }

            outBillDtlGridControl.DataSource = _wrap.POutStoreBillDtl;

            if (outStoreTypeLookUpEdit != null)
            {
                outStoreTypeLookUpEdit.DataBindings.Clear();
                outStoreTypeLookUpEdit.DataBindings.Add("EditValue", _wrap.POutStoreBill, "ExtVarChar1");
            }

            //[start comment 1190]  added by henrik.xia at 2010.10.14，新增两个字段，最后归还日期，故障原因，是借用出库和维修出库使用的。
            if (FBorrowRepairEditor != null)
            {
                //2010.10.21 屏蔽
                //FBorrowRepairEditor.AddRelativeCaptionConrol(FProjectNoOrRepairTrade,"维修商名称：","项目管理号：");
                FBorrowRepairEditor.DataBinding(_wrap.POutStoreBill);
            }
            //[end comment 1190]
        }

        public void RemoveOutStoreBillDtl(OutStoreBillDtl dtl)
        {
            if (_wrap.POutStoreBill.BillState == Constant.BillStateDraft)
            {
                if (dtl.WcfEntityState == EntityState.Added)
                {
                    _wrap.POutStoreBillDtl.Remove(dtl);
                    outBillDtlGridControl.RefreshDataSource();
                }
                else
                {
                    try
                    {
                        if (DialogResult.Yes ==
                            XtraMessageBox.Show("确实要删除该明细吗？", "提问", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                        {
                            WmsServiceFactory.GetServiceClient().DeleteOutStoreBillDtl(dtl);
                            _wrap.POutStoreBillDtl.Remove(dtl);
                            outBillDtlGridControl.RefreshDataSource();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.ShowException(ex);
                    }
                }
            }
            //wrap.POutStoreBillDtl.Remove(dtl);
            //outBillDtlGridControl.RefreshDataSource();
        }

        public void AddOutStoreBillDtl()
        {
            if (_wrap != null)
            {
                var form = new FormOutStoreSelect();
                form.ShowDialog();
                if (form.DialogResult != DialogResult.OK)
                {
                    return;
                }
                var list = form.ExtendStoreGoodsList;

                AddToOutStoreBillDtls(list);

                outBillDtlGridControl.RefreshDataSource();
            }
        }

        public void AddOutStoreBillDtlByImport()
        {
            try
            {
                var openFile = new OpenFileDialog { Filter = @"*.xls|*.xls" };
                if (DialogResult.OK == openFile.ShowDialog())
                {
                    IOutStoreBillExcelImport billExcelImport = new OutStoreBillExcelImport();
                    var list = billExcelImport.ReadExtendStoreGoodsListFromExcel(openFile.FileName);
                    AddToOutStoreBillDtls(list);
                    outBillDtlGridControl.RefreshDataSource();
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.ShowException(exception);
            }
        }

        public CheckEdit CustomInStoreBillId { get; set; }

        public void NewStockTacking(List<StockTackingDtl> dtl)
        {
            this.NewOutStoreBill();
            this._wrap.POutStoreBill.ExtVarChar1 = "002";
            var list = new List<ExtendStoreGoods>();
            var client = Factory.WmsServiceFactory.GetServiceClient();
            foreach (var stockTackingDtl in dtl)
            {
                if(stockTackingDtl.StockQuantity != stockTackingDtl.StockTackingQuantity)
                {
                    var extendStoreGoodsList =
                        client.GetExtendStoreGoodsListByCondition(String.Format(" and NewGoodsCode='{0}'",stockTackingDtl.NewGoodsCode));
                    if(extendStoreGoodsList.Count != 1)
                    {
                        XtraMessageBox.Show(String.Format("不存在物料代码{0}", stockTackingDtl.NewGoodsCode), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        extendStoreGoodsList[0].Quantity = 
                            (stockTackingDtl.StockQuantity??0) - (stockTackingDtl.StockTackingQuantity??0);

                        //此处用作过度，将盘库明细的guid放入此对象，然后将此对象放入出库明细的ObligateChar1字段中。
                        extendStoreGoodsList[0].ObligateChar1 = stockTackingDtl.StockTackingDtlNo;

                        list.Add(extendStoreGoodsList[0]);
                    }
                }
            }
            AddToOutStoreBillDtls(list);
        }

        //public void   AddOutStoreBillDtls(List<ExtendStoreGoods> list)
        //{
        //    AddToOutStoreBillDtls(list);
        //}

// ReSharper disable ParameterTypeCanBeEnumerable.Local
        private void AddToOutStoreBillDtls(List<ExtendStoreGoods> list)
// ReSharper restore ParameterTypeCanBeEnumerable.Local
        {
            foreach (var extendStoreGoods in list)
            {
                var goods = extendStoreGoods;
                var listDtlTmp = _wrap.POutStoreBillDtl.FindAll(billDtl =>
                                                                String.Equals(billDtl.NewGoodsCode,
                                                                              goods.NewGoodsCode)
                                                                &&
                                                                String.Equals(billDtl.SpecificationType,
                                                                              goods.SpecificationType));
                if (listDtlTmp.Count > 0)
                {
                    continue;
                }
                var idx = 0;
                if (_wrap.POutStoreBillDtl.Count > 0)
                {
                    idx = _wrap.POutStoreBillDtl.Select(e => e.Idx).Max();
                }
                var dtl = OutStoreBillDtl.CreateOutStoreBillDtl(_wrap.POutStoreBill.BillID);
                dtl.NewGoodsCode = extendStoreGoods.NewGoodsCode;
                dtl.NewGoodsName = extendStoreGoods.NewGoodsName;
                dtl.OldGoodsCode = extendStoreGoods.OldGoodsCode;
                dtl.PriceNotTax = extendStoreGoods.PriceNotTax;
                dtl.PriceTax = extendStoreGoods.PriceTax;
                dtl.Quantity = extendStoreGoods.Quantity;
                dtl.StoreTypeCode = extendStoreGoods.StoreTypeCode;
                dtl.StoreTypeName = extendStoreGoods.StoreTypeName;
                dtl.TaxRate = extendStoreGoods.TaxRate;
                dtl.UnitCode = extendStoreGoods.UnitCode;
                dtl.UnitName = extendStoreGoods.UnitName;
                dtl.AmountNotTax = extendStoreGoods.AmountNotTax;
                dtl.AmountTax = extendStoreGoods.AmountTax;
                //存储库存表的主键
                dtl.ExtNumeric1 = extendStoreGoods.RowID;
                //存储该物料的安全库存
                dtl.ExtNumeric2 = extendStoreGoods.SafeStoreQty;

                //0817 added by xiaxilin
                dtl.SpecificationType = extendStoreGoods.SpecificationType;

                //1117 added by henrik，库位
                dtl.StoreLocation = extendStoreGoods.ExtVarChar8;

                //2011-03-09 added by henrik
                dtl.ObligateChar1 = extendStoreGoods.ObligateChar1;

                dtl.WcfEntityState = EntityState.Added;
                dtl.Idx = idx + 1;
                _wrap.POutStoreBillDtl.Add(dtl);
            }
        }

        public void NewOutStoreBill()
        {
            if (_wrap != null)
            {
                if (_wrap.IsNeedSaved())
                {
                    if (DialogResult.OK ==
                        XtraMessageBox.Show(_wrap.POutStoreBill.BillID + "当前出库单已修改，要保存吗？", "提问",
                                            MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        SaveOutStoreBill();
                    }
                }
            }
            _wrap = new OutStoreBillWrap();
            _wrap.POutStoreBill = OutStoreBill.CreateOutStoreBill();
            _wrap.POutStoreBillDtl = new List<OutStoreBillDtl>();
            _controlType = ControlType.New;
            DataBinding();
        }

        private bool Save()
        {
            if (_wrap != null && _wrap.POutStoreBill != null && _wrap.POutStoreBillDtl != null)
            {
                if (_wrap.POutStoreBillDtl.Count == 0)
                {
                    XtraMessageBox.Show("明细数量不能为零", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }

                if (_wrap.POutStoreBill.WcfEntityState == EntityState.Added)
                {
                    //取号
// ReSharper disable InconsistentNaming
                    var billID = string.Empty;
// ReSharper restore InconsistentNaming

                    if (this.CustomInStoreBillId.Checked)
                    {
                        var form = new FormInputOutBillId(billID);
                        form.Label = "出库单号(大于5)：";
                        form.ValidateInputId += (string v, out string m) =>
                                                    {
                                                        m = "";
                                                        var list = Factory.WmsServiceFactory.GetServiceClient().
                                                            GetOutStoreBillsByCondition(
                                                                String.Format(" and BillID='{0}'", v));
                                                        if (list.Count > 0)
                                                        {
                                                            m = "该出库单号已经存在！";
                                                            return false;
                                                        }
                                                        return true;
                                                    };
                        if (DialogResult.OK == form.ShowDialog())
                        {
                            billID = form.InputId;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        billID = WmsServiceFactory.GetServiceClient().GetOutStoreBillID();
                    }
                    _wrap.POutStoreBill.BillID = billID;
                    if (_wrap.POutStoreBillDtl.Count > 0)
                    {
                        foreach (var dtl in _wrap.POutStoreBillDtl)
                        {
                            dtl.BillID = billID;
                        }
                    }
                    var wrapService = EntityServiceFactory.GetWrapService<OutStoreBillWrap, OutStoreBillWrapService>();
                    wrapService.SaveWrap(_wrap);
                }
                else
                {
                    var wrapService = EntityServiceFactory.GetWrapService<OutStoreBillWrap, OutStoreBillWrapService>();
                    wrapService.SaveWrap(_wrap);
                }
                _controlType = ControlType.Saved;
                return true;
            }
            return false;
        }

        public void SaveOutStoreBill()
        {
            try
            {
                if (Save())
                {
                    XtraMessageBox.Show(_wrap.POutStoreBill.BillID + "保存成功！", "提示", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    LoadOutStoreBill(_wrap.POutStoreBill.BillID);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.ShowException(ex);
            }
        }

        public void AffirmOutStoreBill()
        {
            try
            {
                if (! Save())
                {
                    return;
                }
                var confirm = ControllerFactory.GetConfirmWrap(_wrap.POutStoreBill.OutBillDate,ConfirmInOutType.Out);
                //if (DialogResult.OK == XtraMessageBox.Show("确实要确认出库吗？", "提问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                if (confirm.IsConfirmOk)
                {
                    _wrap.POutStoreBill.OutBillDate = confirm.ConfirmDate;
                    if (_wrap.POutStoreBillDtl.Count == 0)
                    {
                        XtraMessageBox.Show("出库单至少需要一条物料明细！", "警告", MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        return;
                    }

                    if (_wrap.POutStoreBill.OutBillDate == null)
                    {
                        XtraMessageBox.Show("请输入出库日期！", "警告", MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        return;
                    }

                    WmsServiceFactory.GetServiceClient().AffirmOutStoreBill2(_wrap.POutStoreBill.BillID,
                                                                             confirm.ConfirmDate);
                    _controlType = ControlType.Saved;
                    LoadOutStoreBill(_wrap.POutStoreBill.BillID);
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.ShowException(ex);
            }
        }

        internal void Print<T>() where T : IReportOutput
        {
            if (_wrap.POutStoreBill != null)
            {
                var output = (IReportOutput) typeof (T).Assembly.CreateInstance(typeof (T).ToString());
                output.ShowReport(_wrap.POutStoreBill.BillID);
            }
        }
    }
}